package com.action.Interceptor;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.entity.User;

public class UrlFilter implements Filter{
	private FilterConfig filterConfig = null;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		 this.filterConfig = filterConfig;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req= (HttpServletRequest) request;
		String[] excludePages = filterConfig.getInitParameter("exclude").split(",");
		String servletPath = req.getServletPath();
		
		boolean flag = false;
		for (String excludePage : excludePages) {
			excludePage = excludePage.trim();
			if(excludePage.toCharArray()[0] == '.'){
				flag = flag || (servletPath.endsWith(excludePage));
			}else{
				String sp = servletPath.replace(excludePage, "");
				flag = flag || (sp.equals("") || !sp.contains("/"));
			}
			if(flag) break;
		}
		
		if(flag){
			chain.doFilter(request, response);
		}else{
			User user = (User) req.getSession().getAttribute("user");
			if(user != null){
				chain.doFilter(request, response);
			}else{
				((HttpServletResponse) response).sendRedirect(filterConfig.getInitParameter("loginJsp"));
			}
		}
	}

	@Override
	public void destroy() {
		
	}

}
